package cn.edu.zsc.study.framework.security;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ljx
 */
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {
    JwtLoginFilter(){
        super(new AntPathRequestMatcher("/jwtLogin","GET"));
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException{
           try{
               String username = request.getParameter("username");
               String password = request.getParameter("password");

               JwtLoginToken jwtLoginToken = new JwtLoginToken(username,password);
               jwtLoginToken.setDetails(new WebAuthenticationDetails(request));
               Authentication authenticatedToken = this.getAuthenticationManager().authenticate(jwtLoginToken);
               return authenticatedToken;
           }catch (Exception e){
               throw new BadCredentialsException("损坏认证");
           }
    }
}
